<template>
  <div class="el_main_con">
    <Breadcrumb></Breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="userListParams.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="adduser()">添加用户</el-button>
          <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%">
            <el-form :model="AddUserForm" :rules="AddUserFormRules" ref="AddUserForm" label-width="90px">
              <el-form-item label="用户名称" prop="username">
                <el-input v-model="AddUserForm.username"></el-input>
              </el-form-item>
              <el-form-item label="用户密码" prop="password">
                <el-input v-model="AddUserForm.password" show-password></el-input>
              </el-form-item>
              <el-form-item label="邮   箱" prop="email">
                <el-input v-model="AddUserForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="AddUserForm.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="resetAddForm()">取 消</el-button>
              <el-button type="primary" @click="addUserInfo()">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <div class="controllerbox">
              <el-tooltip effect="dark" content="编辑" placement="top-start">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
              </el-tooltip>
              <el-popconfirm title="确定删除改用户吗？" @onConfirm="deleteUser(scope.row)">
                <el-button slot="reference" type="danger" class="deleBtn" icon="el-icon-delete" size="mini"></el-button>
              </el-popconfirm>
              <el-tooltip effect="dark" content="分配角色" placement="top-start">
                <el-button type="warning" icon="el-icon-s-tools" size="mini" @click="openAddRoleBox(scope.row)"></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationBox">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="userListParams.pagenum" :page-sizes="[2,5,10]" :page-size="userListParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>
    <el-dialog title="编辑用户" :visible.sync="editDialog" width="30%">
      <el-form :model="EditUserForm" :rules="EditUserFormRules" ref="EditUserForm" label-width="90px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="EditUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮   箱" prop="email">
          <el-input v-model="EditUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="EditUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetEditForm()">取 消</el-button>
        <el-button type="primary" @click="EditUserInfo()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="addRolesVisible" width="30%">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配角色：
          <el-select v-model="selectRoleValue" placeholder="请选择">
            <el-option v-for="item in userRoleList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddRole()">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Users } from '../../api/apiConfig'
import Breadcrumb from 'components/breadcrumb/breadcrumb'
export default {
  components: {
    Breadcrumb
  },
  data () {
    const validatorEmail = (rule, value, callback) => {
      var reg = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      if (!value) {
        callback()
      }
      if (!reg.test(value)) {
        callback(new Error('邮箱格式不正确'))
      }
    }
    const validatorMobile = (rule, value, callback) => {
      var reg = /^(13|14|15|17|18)\d{9}$/
      if (!value) {
        callback()
      }
      if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      userList: [],
      total: 0,
      userListParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      dialogVisible: false,
      editDialog: false,
      AddUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      EditUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      AddUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' }
        ],
        email: [
          { validator: validatorEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: validatorMobile, trigger: 'blur' }
        ]
      },
      EditUserFormRules: {
        email: [
          { validator: validatorEmail, trigger: 'blur' }
        ],
        mobile: [
          { validator: validatorMobile, trigger: 'blur' }
        ]
      },
      addRolesVisible: false,
      userInfo: {},
      userRoleList: [],
      selectRoleValue: ''
    }
  },
  watch: {
    // el-input中的@clear="getUserList()"事件可以代替一下操作
    // 'userListParams.query': function (newVal) {
    //   if (!newVal) {
    //     this.getUserList()
    //   }
    // }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    getUserList () {
      Users.getUserList(this.userListParams).then(res => {
        if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
        this.userList = res.data.users
        this.total = parseInt(res.data.total)
      })
    },
    handleSizeChange (newSize) {
      this.userListParams.pagesize = newSize
      this.getUserList(this.userListParams)
    },
    handleCurrentChange (newPage) {
      this.userListParams.pagenum = newPage
      this.getUserList(this.userListParams)
    },
    userStateChange (userInfo) {
      const url = `users/${userInfo.id}/state/${userInfo.mg_state}`
      const params = {}
      Users.userStateChange(url, params).then(res => {
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('更新用户状态失败')
        }
        return this.$message.success('更新用户状态成功')
      })
    },
    adduser () {
      this.dialogVisible = true
    },
    resetAddForm () {
      this.dialogVisible = false
      this.$refs.AddUserForm.resetFields()
    },
    addUserInfo () {
      this.$refs.AddUserForm.validate((valid) => {
        if (!valid) return false
      })
      const params = {
        username: this.AddUserForm.username,
        password: this.AddUserForm.password,
        email: this.AddUserForm.email,
        mobile: this.AddUserForm.mobile
      }
      Users.addUserInfo(params).then(res => {
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.dialogVisible = false
        this.$refs.AddUserForm.resetFields()
        this.getUserList()
      })
    },
    showEditDialog (userInfo) {
      this.editDialog = true
      this.EditUserForm = {
        id: userInfo.id,
        username: userInfo.username,
        email: userInfo.email,
        mobile: userInfo.mobile
      }
    },
    resetEditForm () {
      this.editDialog = false
      this.$refs.EditUserForm.resetFields()
    },
    EditUserInfo () {
      const url = `users/${this.EditUserForm.id}`
      const params = {
        email: this.EditUserForm.email,
        mobile: this.EditUserForm.mobile
      }
      Users.editUserInfo(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editDialog = false
        this.getUserList()
        this.$refs.EditUserForm.resetFields()
      })
    },
    deleteUser (userInfo) {
      const url = `users/${userInfo.id}`
      Users.deleteUserInfo(url).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    openAddRoleBox (userInfo) {
      this.addRolesVisible = true
      this.userInfo = userInfo
      Users.getUserRoleList().then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userRoleList = res.data
      })
    },
    closeAddRole () {
      this.addRolesVisible = false
      this.selectRoleValue = ''
    },
    addRole () {
      const url = `users/${this.userInfo.id}/role`
      const params = {
        rid: this.selectRoleValue
      }
      Users.addUserRole(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addRolesVisible = false
        this.selectRoleValue = ''
        this.getUserList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
